package org.example.server.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.util.JSON;
import org.bson.Document;
import org.example.server.model.core.Rating;
import org.example.java.model.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import scala.Array;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class RatingService {

    @Autowired
    private MongoClient mongoClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private Jedis jedis;

    private Document ratingToDocument(Rating rating) {
        try {
            Document document = Document.parse(objectMapper.writeValueAsString(rating));
            return document;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Rating documentToRating(Document document) {
        try {
            Rating rating = objectMapper.readValue(JSON.serialize(document), Rating.class);
            return rating;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    public void rateToMovie(Rating rating) {
        MongoCollection<Document> ratingCollection = mongoClient.getDatabase(Constant.MONGO_DATABASE).getCollection(Constant.MONGO_RATING_COLLECTION);

        // 构建查询条件
        Document query = new Document();
        query.put("uid", rating.getUid());
        query.put("mid", rating.getMid());

        Document document = ratingCollection.find(query).first();

        // 如果已经有该用户对该电影的评分，则先删掉旧的再覆盖新的
        if (null == document || document.isEmpty()) {
        }else{
            ratingCollection.deleteOne(document);
        }

        ratingCollection.insertOne(ratingToDocument(rating));
        //  更新redis
        updateRedis(rating);
    }


    private void updateRedis(Rating rating) {
        if (jedis.llen("uid:" + rating.getUid()) >= Constant.USER_RATING_QUEUE_SIZE) {
            jedis.rpop("uid:"+ rating.getUid());
        }
        jedis.lpush("uid:"+ rating.getUid(), rating.getMid()+":"+rating.getScore());
    }

    public List<Rating> getUserRatings(int uid){
        MongoCollection<Document> ratingCollection = mongoClient.getDatabase(Constant.MONGO_DATABASE).getCollection(Constant.MONGO_RATING_COLLECTION);

        List<Rating> result = new ArrayList<>();
        FindIterable<Document> documents = ratingCollection.find(new Document("uid", uid));

        for (Document document : documents) {
            // 处理每个文档的数据
            result.add(documentToRating(document));
        }

        return result;
    }
}
